var _columns = [
	{checkbox: true},
	{field: 'id', title: '标示符', align: 'center',	 valign: 'middle'},
	{title: '序号', field: 'showId', align: 'center',	 valign: 'middle',
		formatter:function(value,row,index){
			return index+1;
	}},
	{field: 'roleName', title: '角色名称', sortable: true},
    //{field: 'note', title: '备注', sortable: true},
    {field: 'createdAt', title: '创建日期', sortable: true,
        formatter:function(value, row, index) {
            return row.createdAt
        }
    },
    {field: 'operation', title:'权限',
        formatter:function(value,row,index) {
                var e = '<a href="#" mce_href="#" onclick="edit(\''+ row.id + '\',\'' + row.roleName + '\')"><i class="fa fa-edit" ></i>编辑</a>';
                return e;
        }
    },
    {field: 'note', title: '备注', sortable: true},
]


$('.selectpicker').selectpicker('val', 'mustard');
$('.selectpicker').selectpicker('val', ['mustard', 'relish']);
$('.selectpicker').selectpicker('refresh');


var TableInit = function () {
    var oTableInit = new Object();
    oTableInit.Init = function () {
        $('#data_table').bootstrapTable({
            url: '/roles/select-by-company-id',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            sortable: true,                     //是否启用排序
            sortOrder: "desc",                  //排序方式
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            companyId: edit_id,
        };
        return temp;
    };
    return oTableInit;
};

var ButtonInit = function () {
    var oInit = new Object();

    oInit.Init = function () {
        //初始化页面上面的按钮事件
        //新增按钮
        $("#btn_return").click(function() {
            page_name = "公司管理"
            $('#page-wrapper').load('pages/companys.html');
        })
        $("#btn_add").click(function () {
        	$('#new_role_name').val("");
        	$('#new_role_note').val("")
            $('#new_data').modal();
        });


        //新增框内的提交
        $('#new_data_submit').on('click', function () {
        	var roleName = $('#new_role_name').val()
            var note = $("#new_role_note").val()
            var roleDate = new Date();

            if (roleName == "" || roleName == null){
				bootoast({
                    message: '请输入角色名称',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
			}
            $.ajax({
                type: "post",
                url: "/roles/insert",
                async:false,
                data: {
                    'createdAt':roleDate,
                	'roleName':roleName,
                    'note':note,
                    'companyId': edit_id,
                },
                success: function (data) {
                    if (data['status'] == "success") {
                        bootoast({
                            message: '插入成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#new_data").modal('hide');
                        $('#new_role_name').val("")
                        $('#new_role_note').val("")
                        $("#data_table").bootstrapTable('refresh')
                    } else {
                        bootoast({
                            message: '插入失败\n' + data['msg'],
                            position: 'top',
                            type: 'danger',
                            timeout: 2,
                        });
                    }
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
        });

        //编辑按钮
        $("#btn_edit").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            $('#edit_role_name').val(arrselections[0]['roleName']);
            $('#edit_role_note').val(arrselections[0]['note'])
            $('#edit_data').modal()
            //加载时间组件
        });

        //编辑框内的提交
        $('#edit_data_submit').click(function () {
            var id = $("#data_table").bootstrapTable('getSelections')[0]['id'];
            var roleName = $('#edit_role_name').val();
            var note = $('#edit_role_note').val()
            var roleDate = new Date();
            $.ajax({
                type: "post",
                url: "/roles/update",
                async:false,
                data: {
                    'id':id,
                    'roleName':roleName,
                    'note':note,
                    'createdAt': roleDate,
                },
                success: function (data) {
                    if (data['status'] == "success") {
                        bootoast({
                            message: '修改成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#edit_data").modal('hide');
                        $("#data_table").bootstrapTable('refresh');
                    } else {
                        bootoast({
                            message: '修改失败\n' + data['msg'],
                            position: 'top',
                            type: 'danger',
                            timeout: 2,
                        });
                    }
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
        });
        //搜索按钮
        $('#btn_search').click(function () {
            $('#search_content').val("");
            $('#search_data').modal();

            //$('#data_table').bootstrapTable('remove', {field: 'companyName', values: str})
        });

        //搜索框提交
        //搜索框内的提交
        $('#search_data_submit').click(function() {
            var ids = [];
            var searchContent = $('#search_content').val();
            var data = $('#data_table').bootstrapTable('getData', false);//获取所有数据
            for(var i = 0; i < data.length; i++) {
                var flag = false;
                for(var prop in data[i]) {
                    if(prop == 'createdAt' || prop == 'roleName' || prop == 'note' ) {
                        if(String(data[i][prop]).indexOf(String(searchContent)) != -1) {
                            //alert(String(data[i][prop]));
                            flag = true;
                            break;
                        }
                    }
                }
                if(!flag) {
                    ids.push(parseInt(data[i]['id']));
                }
            }
            $('#data_table').bootstrapTable('remove', {'field': 'id', 'values': ids});
            $('#search_data').modal('hide');
        });

        // 删除按钮
        $("#btn_delete").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            values=[];
            for(var i=0;i<arrselections.length;i++)
                values.push(arrselections[i].id);
            bootbox.confirm({
                message: "确认要删除选择的数据吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/roles/delete",
                            async:false,
                            data: JSON.stringify(values),
                            contentType: "application/json",
                            success: function (data) {
                                if (data['status'] == "success") {
                                    bootoast({
                                        message: '删除成功',
                                        position: 'top',
                                        type: 'success',
                                        timeout: 1.5,
                                    });
                                } else if(data['status'] == "failed"){
                                    bootoast({
                                        message: '删除失败',
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                                else if(data['status'] == "used"){
                                    bootoast({
                                        message: '删除失败'+data['msg'],
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                                $("#data_table").bootstrapTable('refresh');
                            }
                        });
                    }
                }
            })
        });

        //权限选择提交按钮
        $("#tree-select-submit").click(function() {
            let value = $('#tree-select-root').val()
            let values = ["" + label_id]
            if(value) {
                for (let i = 0; i < value.length; i++) {
                    values.push(value[i])
                }
            }
            bootbox.confirm({
                message: "确认要分配给[ " + label_role_name + "] 角色所选权限吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/authority/update-authority",
                            async:false,
                            data: JSON.stringify(values),
                            contentType: "application/json",
                            success: function (data) {
                                if (data['status'] == "success") {
                                    bootoast({
                                        message: '保存成功',
                                        position: 'top',
                                        type: 'success',
                                        timeout: 1.5,
                                    });
                                    $("#data_table").bootstrapTable('refresh');
                                    $("#tree_select").modal('hide')
                                } else {
                                    bootoast({
                                        message: '保存失败\n' + data['msg'],
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            }
                        });
                    }
                }
            })
        })
    };
    return oInit;
};

function hasPermission() {
    queryPermission('权限管理/企业管理/角色管理', '新增', 'btn_add')
    queryPermission('权限管理/企业管理/角色管理', '编辑', 'btn_edit')
    queryPermission('权限管理/企业管理/角色管理', '删除', 'btn_delete')
}

$(function () {
    show_page_name();
    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    //3.隐藏列
    $('#data_table').bootstrapTable('hideColumn', 'id');
    hasPermission()
});

//小函数
//获取当前时期 yyyy-mm-dd
function getdate() {
	var date = new Date();
	var mon = date.getMonth()  + 1;         //getMonth()返回的是0-11，则需要加1
	if(mon <=9){                                     //如果小于9的话，则需要加上0
	    mon = "0" + mon;
	}
	var day = date.getDate();                   //getdate()返回的是1-31，则不需要加1
	if(day <=9){                                     //如果小于9的话，则需要加上0
	    day = "0" + day;
	}
	var date_info = date.getFullYear() + "-" + mon + "-" +  day;
	return date_info;
}

function create_tree_column(row) {
    if(row.isHave == 0) {
        let str = '<option value="' + row['id'] + '" data-section="' + row['authName'] + '">' + row.info + '</option>'
        return str
    }
    else {
        let str = '<option value="' + row['id'] + '" data-section="' + row['authName'] + '" selected="selected">' + row.info + '</option>'
        return str
    }
}


var label_id;
var label_role_name;
function edit(id, roleName) {
    label_id = id;
    label_role_name = roleName;

    $('#tree-select-div').empty()
    $('#tree-select-div').append('<select id="tree-select-root" class="selectpicker" multiple="multiple"></select>')

    $.ajax({
        type: 'get',
        url: '/authority/select',
        async: false,
        data: {
            'roleId': label_id,
        },
        success: function (data) {
            if(data.rows.length > 0) {
                for (let i = 0; i < data.rows.length; i++) {
                    let str = create_tree_column(data.rows[i]);
                    $('#tree-select-root').append(str)
                }
            }
            $('#tree-select-root').treeMultiselect({
                startCollapsed: true,
            })
        }
    });
    $("#tree_select").modal()
}

function show_page_name() {
     var mystr=document.getElementById('page_name');
     mystr.innerHTML=page_name;
}